<template>
  <van-popup v-model:show="flavorPopup" round @click-overlay="onClickOverlay" style="width: 300px;">
    <div style="height: 46px; line-height: 46px; text-align: center; background-color: #f5f5f5">
      {{ item.name }}
    </div>
    <div v-for="it in item.flavors" :key="it.id"
      style="flex: 1; overflow-y: auto; padding: 20px 10px; min-height: 120px">
      <h3>{{ it.name }}</h3>
      <div class="flavor-list">
        <div class="flavor-item" v-for="option in JSON.parse(it.value)" :key="option"
          :class="{ selected: selectedFlavors[it.id] === option }" @click="selectFlavor(it.id, option)">
          {{ option }}
        </div>
      </div>
    </div>
    <div class="flavor-bottom">
      <span>
        已选规格:<span style="color: #ff0000; padding-left: 5px">{{ getSelectedFlavorString || '未选择' }} </span></span>
      <button @click="addCart" :class="getSelectedFlavorString === '' ? 'disable-btn' : 'add-cart'"
        :disabled="getSelectedFlavorString === ''">加入购物车</button>
    </div>
  </van-popup>
</template>
<script setup lang="ts">
import type { DishFlavor } from '@/types/meal.d.ts'
import { ref, computed } from "vue"
const props = defineProps({
  item: { type: Object, default: () => { } }
})
const flavorPopup = defineModel<boolean>('flavorPopup')
const emits = defineEmits(['addCart'])
// 选择的口味
const selectedFlavors = ref<Record<number, string>>({});
// 选择菜品口味
const selectFlavor = (flavorId: number, option: string) => {
  selectedFlavors.value[flavorId] = option;
};

const getSelectedFlavorString = computed(() => {
  return props.item.flavors
    .map((flavor: DishFlavor) => {
      const selected = selectedFlavors.value[flavor.id];
      return selected ? `${flavor.name}:${selected}` : '';
    })
    .filter(Boolean)
    .join(';');
});

const addCart = () => {
  emits('addCart',props.item, getSelectedFlavorString.value)
  flavorPopup.value = false
}
// 关闭口味选择弹窗
const onClickOverlay = () => {
  selectedFlavors.value = ''
}
</script>
<style scoped lang="scss">
.selected {
  border-color: #ff4d4f;
  background-color: #fff2f0;
  color: #ff4d4f;
}
</style>
